# RootPage.py
import sys
import tkinter as tk
from tkinter import ttk, scrolledtext
import os
from utils.usbWatcher import UsbWatcher

from pages.android_checkingtoolpage import Android_CheckToolPage
from pages.harmonyOS_checktoolpage import HarmonyOS_CheckToolPage
from pages.iOS_checktoolpage import iOS_CheckToolPage

# ---------- 网页风浅色主题 ----------
BG_LIGHT   = "#ffffff"          # 主背景
SIDEBAR_BG = "#f5f5f5"          # 侧边栏背景
ACCENT     = "#2563eb"          # 主色调（蓝色）
TEXT_DARK  = "#1e293b"          # 主文字
TEXT_MUTED = "#64748b"          # 次要文字
BORDER     = "#e2e8f0"          # 边框

class RootPage(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("Cross-Platform Packing Tool")
        self.set_geometry(0.6, 0.7)
        self.configure(bg=BG_LIGHT)
        self.resizable(True, True)
        self.container = None
        self.current_page = None
        self._alive = True

        self._setup_styles()
        self._setup_ui()
        self._setup_help_text()

        # 图标设置
        self._set_icon()

        # 默认页面
        self.show_harmonyos_checktool_page()

        self.usb_watcher = UsbWatcher(callback=self._on_usb_change)
        self.usb_watcher.start()
        self.protocol("WM_DELETE_WINDOW", self.destroy)

    # ------------------------------------------------------------------
    # 样式
    # ------------------------------------------------------------------
    def _setup_styles(self):
        style = ttk.Style(self)
        style.theme_use("clam")

        # 主框架
        style.configure("TFrame", background=BG_LIGHT)
        style.configure("Sidebar.TFrame", background=SIDEBAR_BG)

        # 侧边栏按钮：极简白灰风
        style.configure(
            "Soft.TButton",
            background=SIDEBAR_BG,
            foreground=TEXT_DARK,
            borderwidth=0,
            focusthickness=0,
            font=("Segoe UI", 11),
            relief=tk.FLAT,
            anchor="w",
            padding=(12, 10)
        )
        style.map(
            "Soft.TButton",
            background=[("active", "#e2e8f0"), ("pressed", "#cbd5e1")],
            foreground=[("active", ACCENT), ("pressed", ACCENT)]
        )

    # ------------------------------------------------------------------
    # 图标设置
    # ------------------------------------------------------------------
    def _set_icon(self):
        icon_path = "resources/icon.ico"
        if os.path.exists(icon_path):
            self.iconbitmap(icon_path)
        else:
            print("⚠️ 未找到 icon.ico，窗口图标将使用默认")

    # ------------------------------------------------------------------
    # 界面构建
    # ------------------------------------------------------------------
    def _setup_ui(self):
        main = ttk.Frame(self, style="TFrame")
        main.pack(fill=tk.BOTH, expand=True)

        # 侧边栏
        sidebar = ttk.Frame(main, style="Sidebar.TFrame")
        sidebar.pack(side=tk.LEFT, fill=tk.Y, ipadx=10, ipady=10)

        # Logo
        logo = ttk.Label(sidebar, text="🚀 CPPT", font=("Segoe UI", 22, "bold"), foreground=TEXT_DARK)
        logo.pack(pady=(20, 10))

        # 图标路径
        icon_dir = os.path.join("resources")
        icons = {
            "ios": os.path.join(icon_dir, "APPLE.png"),
            "harmony": os.path.join(icon_dir, "HUAWEI.png"),
            "android": os.path.join(icon_dir, "Android.png"),
        }

        # 按钮列表（带 PNG 图标）
        buttons = [
            ("iOS 一键打包", icons["ios"], self.show_ios_checktool_page),
            ("鸿蒙一键打包", icons["harmony"], self.show_harmonyos_checktool_page),
            ("安卓一键打包", icons["android"], self.show_android_checktool_page),
            ("❓ 使用说明", None, self._show_help_dialog)
        ]

        for text, img_path, cmd in buttons:
            try:
                img = tk.PhotoImage(file=img_path).subsample(2, 2) if img_path else None
            except Exception:
                img = None
            btn = ttk.Button(sidebar, text=text, image=img, compound="left", style="Soft.TButton", command=cmd)
            if img:
                btn.image = img
            btn.pack(fill=tk.X, padx=10, pady=6, ipady=6)

        # 右侧容器（用于切换页面）
        self.container = ttk.Frame(main, style="TFrame")
        self.container.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)

    # ------------------------------------------------------------------
    # 页面切换
    # ------------------------------------------------------------------
    def show_ios_checktool_page(self):
        if self.current_page:
            self.current_page.destroy()
        self.current_page = iOS_CheckToolPage(self.container)

    def show_harmonyos_checktool_page(self):
        if self.current_page:
            self.current_page.destroy()
        self.current_page = HarmonyOS_CheckToolPage(self.container)

    def show_android_checktool_page(self):
        if self.current_page:
            self.current_page.destroy()
        self.current_page = Android_CheckToolPage(self.container)

    # ------------------------------------------------------------------
    # 使用说明
    # ------------------------------------------------------------------
    # ------------------------------------------------------------------
    # 使用说明弹窗
    # ------------------------------------------------------------------
    def _show_help_dialog(self):
        help_win = tk.Toplevel(self)
        help_win.title("使用说明")
        help_win.resizable(False, False)                     # 固定大小
        help_win.geometry("480x360")                         # 适中说明书尺寸
        help_win.configure(bg=BG_LIGHT)
        help_win.transient(self)
        help_win.grab_set()

        # 设置窗口图标（根据当前系统选择 .ico 或 .png）
        try:
            if getattr(sys, 'frozen', False):
                # PyInstaller 打包后的路径
                base_path = sys._MEIPASS
            else:
                icon_path = os.path.join("resources", "icon.ico" if os.name == 'nt' else "icon.png")
            if os.path.exists(icon_path):
                help_win.iconbitmap(icon_path) if os.name == 'nt' else help_win.tk.call('wm', 'iconphoto', help_win._w, tk.PhotoImage(file=icon_path))
        except Exception:
            pass  # 如果图标不存在也不影响功能

        # 滚动文本框
        text_area = scrolledtext.ScrolledText(
            help_win,
            wrap=tk.WORD,
            bg=BG_LIGHT,
            fg=TEXT_DARK,
            font=("Segoe UI", 11),
            padx=12,
            pady=12,
            relief=tk.FLAT,
            state=tk.NORMAL
        )
        text_area.pack(fill=tk.BOTH, expand=True)
        text_area.insert(tk.INSERT, self.help_text)
        text_area.config(state=tk.DISABLED)

    # ------------------------------------------------------------------
    # 帮助文本内容
    # ------------------------------------------------------------------
    def _setup_help_text(self):
        self.help_text = (
            "欢迎使用 Cross-Platform Packing Tool！\n\n"
            "📱 iOS：需要 macOS 或 WSL2 + Swift + xtool\n"
            "📱 鸿蒙：需要 DevEco Studio / Command-line-tools + hdc\n"
            "📱 安卓：需要 Android Studio + adb\n\n"
            "如果存在环境检测中的部分环境缺少，请先将对应的系统环境变量配置起来！！！(重要)\n"
            "1. 选择项目根目录\n"
            "2. 点击“编译打包”\n"
            "3. 等待上传/构建完成\n"
            "4. 查看结果或者在设备列表中针对已经连接手机右键单机并选择一键安装打出来的安装包\n\n"
            "更多详细信息，请查阅官方文档。"
        )

    # ------------------------------------------------------------------
    # 工具方法
    # ------------------------------------------------------------------
    def set_geometry(self, width_ratio, height_ratio):
        sw = self.winfo_screenwidth()
        sh = self.winfo_screenheight()
        w = int(sw * width_ratio)
        h = int(sh * height_ratio)
        self.geometry(f"{w}x{h}+{(sw - w) // 2}+{(sh - h) // 2}")

    def _on_usb_change(self):
        if hasattr(self.current_page, "on_usb_change"):
            self.current_page.on_usb_change()

    def destroy(self):
        self._alive = False
        self.usb_watcher.stop()
        super().destroy()